/**
 * API接口调用模块
 * 使用fetch API统一处理请求和认证逻辑
 */

// 基础URL
const BASE_URL = '/lzw';

// 通用请求函数
async function request(url, options = {}) {
  // 确保headers存在
  options.headers = options.headers || {};
  
  // 添加认证token
  const token = localStorage.getItem('satoken');
  if (token) {
    options.headers['satoken'] = token;
  }
  
  // 添加内容类型
  if (!options.headers['Content-Type'] && options.method !== 'GET') {
    options.headers['Content-Type'] = 'application/json';
  }
  
  // 添加完整URL
  const fullUrl = `${BASE_URL}${url}`;
  
  try {
    const response = await fetch(fullUrl, options);
    
    // 处理401未授权错误
    if (response.status === 401) {
      console.error('认证失败，请重新登录');
      localStorage.removeItem('satoken');
      window.location.href = '/login?redirect=' + encodeURIComponent(window.location.pathname);
      return Promise.reject('未授权');
    }
    
    // 解析响应
    const data = await response.json();
    
    // 处理业务逻辑错误
    if (data.code !== 200) {
      console.error(`请求错误: ${data.message}`);
      return Promise.reject(data);
    }
    
    return data;
  } catch (error) {
    console.error('请求异常:', error);
    return Promise.reject(error);
  }
}

// GET请求
function get(url, params = {}) {
  // 构建查询参数
  const queryString = Object.keys(params)
    .filter(key => params[key] !== undefined && params[key] !== null)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&');
  
  const fullUrl = queryString ? `${url}?${queryString}` : url;
  
  return request(fullUrl, { method: 'GET' });
}

// POST请求
function post(url, data = {}) {
  return request(url, {
    method: 'POST',
    body: JSON.stringify(data)
  });
}

// PUT请求
function put(url, data = {}) {
  return request(url, {
    method: 'PUT',
    body: JSON.stringify(data)
  });
}

// DELETE请求
function del(url) {
  return request(url, { method: 'DELETE' });
}

// API接口对象
const api = {
  // 用户相关
  user: {
    login: (data) => post('/user/login', data),
    register: (data) => post('/user/register', data),
    info: () => get('/user/info'),
    updatePassword: (oldPassword, newPassword) => post('/user/password', { oldPassword, newPassword }),
    list: (params) => get('/user/page', params),
    add: (data) => post('/user', data),
    update: (data) => put('/user', data),
    delete: (id) => del(`/user/${id}`)
  },
  
  // 权限相关
  permission: {
    tree: () => get('/permission/tree'),
    add: (data) => post('/permission', data),
    update: (data) => put('/permission', data),
    delete: (id) => del(`/permission/${id}`),
    getRolePermissions: (roleId) => get(`/permission/role/${roleId}`),
    getCurrentUserPermissions: () => get('/permission/user')
  },
  
  // 角色相关
  role: {
    list: () => get('/role/list'),
    page: (params) => get('/role/page', params),
    add: (data) => post('/role', data),
    update: (data) => put('/role', data),
    delete: (id) => del(`/role/${id}`),
    assignPermissions: (roleId, permissionIds) => post(`/role/${roleId}/permissions`, permissionIds),
    getUserRoles: (userId) => get(`/role/user/${userId}`),
    assignUserRoles: (userId, roleIds) => post(`/role/user/${userId}`, roleIds)
  },
  
  // 部门相关
  dept: {
    tree: () => get('/dept/tree'),
    add: (data) => post('/dept', data),
    update: (data) => put('/dept', data),
    delete: (id) => del(`/dept/${id}`),
    getChildren: (deptId) => get(`/dept/children/${deptId}`)
  },
  
  // 员工相关
  employee: {
    list: (params) => get('/employee/list', params),
    detail: (id) => get(`/employee/${id}`),
    education: (id) => get(`/employee/${id}/education`),
    workHistory: (id) => get(`/employee/${id}/work-history`),
    certificate: (id) => get(`/employee/${id}/certificate`),
    add: (data) => post('/employee', data),
    update: (data) => put('/employee', data),
    delete: (id) => del(`/employee/${id}`)
  },
  
  // 验证码
  captcha: {
    get: () => get('/auth/captcha')
  }
};

// 导出API
window.api = api; 